package com.axend.aerosense.common.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author ChenHongWei
 * @date :2020/12/29 11:23
 */

public abstract class BaseBindingAdapter<M, B extends ViewDataBinding> extends RecyclerView.Adapter
{
    protected List<M> items;
    private Context context;

    public BaseBindingAdapter(List<M> items){
        this.items = items;
    }

    public BaseBindingAdapter(){}

    @Override
    public int getItemCount()
    {
        return items == null ? 0 : this.items.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        context = parent.getContext();
        B binding = DataBindingUtil.inflate(LayoutInflater.from(context),
                this.getLayoutResId(viewType), parent, false);
        return new BaseBindingViewHolder(binding.getRoot());
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
    {
        B binding = DataBindingUtil.getBinding(holder.itemView);
        this.onBindItem(binding, this.items.get(position), position);
    }

    protected void setItems(List<M> items) {
        this.items = items;
    }

    protected Context getContext() {
        return context;
    }

    //更新列表数据
    public void upDateList(List<M> dateItems){
        if (dateItems != null){
            this.items = dateItems;
            notifyDataSetChanged();

        }
    }

    protected abstract @LayoutRes
    int getLayoutResId(int viewType);

    protected abstract void onBindItem(B binding, M item, int position);
}
